﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using EquipViewAppNet;
using SecsEquip;
using SecsEquip300;

namespace EquipSecs300
{
    public partial class SecsMainForm : CMyFormEx
    {
        // 当前活跃窗口       
        CMyFormEx m_curActiveView = null;
        TitleView m_pTitleView = null;
        FormPassword formPassword = null;
        Dictionary<string, CMyFormEx> m_mapView = new Dictionary<string, CMyFormEx>();
        OnTerminalEventHandler m_pTerminalEventView = null;

        private SecsMainForm(SecsEquipHelper secsEquip)
        {
            secsEquipHelper = secsEquip; ;
            m_pSecs = CSecsEquipInstance.GetSecsInstance(SecsEquipHelper.IsCreateSelf);

            InitializeComponent();
            UpdateData();
        }

        private static readonly object _instanceLock = new object();
        private static SecsMainForm _secsMainForm;
        public static SecsMainForm GetInstance(SecsEquipHelper secsEquip)
        {
            lock (_instanceLock)
            {
                if (_secsMainForm == null)
                {
                    _secsMainForm = new SecsMainForm(secsEquip);
                }
                return _secsMainForm;
            }
        }

        // 更新数据
        new public void UpdateData()
        {
            InitTitle();
            InitTree();
            InitListView();
            InitEvent();
        }

        void InitEvent()
        {
            //m_pSecs.m_pOnTerminal += OnTerminalEventHandler;
            //m_pTerminalEventView += OnTerminalEventShow;
        }

        void InitTitle()
        {
            formPassword = new FormPassword();
            m_pTitleView = new TitleView(formPassword);

            InitView(m_pTitleView);

            m_pTitleView.Show();
            panelTitle.Controls.Add(m_pTitleView);

        }

        void InitTree()
        {
            treeViewFunc.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Bottom;

            // 增加功能列表
            // 层1
            TreeNode nodeTop;
            nodeTop = treeViewFunc.Nodes.Add("Equip");

            // 层2子
            nodeTop.Nodes.Add("Varibles");
            nodeTop.Nodes.Add("Event");
            nodeTop.Nodes.Add("Alarm");
            nodeTop.Nodes.Add("Terminal");
            nodeTop.Nodes.Add("Process");
            nodeTop.Nodes.Add("Remote Control");

            nodeTop.Nodes.Add("PJob");
            nodeTop.Nodes.Add("Load Port");
            nodeTop.Nodes.Add("CJob");
            nodeTop.Nodes.Add("Substrate Tracking");
            nodeTop.Nodes.Add("PPFormat View");
            nodeTop.Nodes.Add("Constant View");
            nodeTop.Nodes.Add("CostomizePP");
            nodeTop.Nodes.Add("Logs");

            nodeTop.Expand();

            // 层1
            nodeTop = treeViewFunc.Nodes.Add("Connect");

            // 层2子
            nodeTop.Nodes.Add("Secs Config");
            nodeTop.Nodes.Add("Function Config");
            nodeTop.Expand();

            ChangePermission(treeViewFunc.Nodes, GlobalVar.IsLogIn);
        }


        // 初始化List
        void InitListView()
        {
            panelShow.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Bottom;

            // 添加初始化界面      
            AddToList("Varibles", new VariablesView());
            AddToList("Event", new EventView());
            AddToList("Alarm", new AlarmView());
            AddToList("Terminal", new TerminalView());
            AddToList("Connect", new ConnectControlView());
            AddToList("Process", new ProcessView());
            AddToList("Remote Control", new RemoteControlView());
            AddToList("Secs Config", new SecsConfig());
            AddToList("PPFormat View", new PPFormatView());
            AddToList("Constant View", new ConstantView());
            AddToList("Function Config", new FunctionConfig());
            AddToList("Logs", new LogsView());

            AddToList("PJob", new PJobView());
            AddToList("Load Port", new LoadPortView(secsEquipHelper));
            AddToList("CJob", new CJobView());
            AddToList("Substrate Tracking", new SubstrateTrackingView());

            // 显示第一个窗口
            ShowView("Connect");

        }

        // 添加数据
        void AddToList(string name, CMyFormEx view)
        {
            InitView(view);

            m_mapView.Add(name, view);
        }

        // 初始化窗口
        private void InitView(CMyFormEx view)
        {
            view.TopLevel = false;
            view.BackColor = Color.White;
            view.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Bottom;
            view.FormBorderStyle = FormBorderStyle.None;
            
            view.m_pMainView = this;
            view.m_pSecs = m_pSecs;
            view.secsEquipHelper = secsEquipHelper;
            view.UpdateData();
            view.Show();
            view.Hide();

            if (view is TerminalView)
            {
                ((TerminalView)view).PopUpWindow += OnTerminalEventHandlerShow;
            }
            formPassword.PassWordLogIn += this.OnPasswordLogin;
            formPassword.PassWordLogIn += view.OnPasswordLogin;

        }

        private void treeViewFunc_AfterSelect(object sender, TreeViewEventArgs e)
        {
            // 获取名称
            TreeNode node = treeViewFunc.SelectedNode;
            string func = node.Text;

            if (GlobalVar.IsLogIn != 1 && (string)node.Tag != "Pass")
            {
                MessageBox.Show("请先登录");
                return;
            }

            ShowView(func);
        }

        // 显示窗口,设为活跃窗口
        void ShowView(string viewName)
        {
            // 获取对象                   
            CMyFormEx view = GetViewForMap(viewName);

            // 设置窗口名称
            labelTitle.Text = viewName;
            if (view != null && view.m_pViewName != null)
            {
                labelTitle.Text = view.m_pViewName;
            }
            if (view is LogsView)
            {
                ShowForm(view);
            }
            else
            {
                AddPaneView(view);
            }
        }

        // 寻找相应的map数据
        CMyFormEx GetViewForMap(string name)
        {
            CMyFormEx view = null;
            try
            {
                view = m_mapView[name];
            }
            catch (System.Exception)
            {
                view = null;
            }
            return view;
        }

        // 
        // 添加显示界面
        void AddPaneView(CMyFormEx view)
        {
            if (view == null)
            {
                return;
            }

            if (m_curActiveView != null)
            {
                m_curActiveView.Hide();
            }
            view.Show();
            view.TopLevel = false;
            view.FormBorderStyle = FormBorderStyle.None;
            view.Location = new Point(0, 0);
            //view.Dock = DockStyle.Fill;
            panelShow.Controls.Add(view);
            m_curActiveView = view;
        }
        void ShowForm(CMyFormEx view)
        {
            if (view == null)
            {
                return;
            }
            view.TopLevel = true;
            view.FormBorderStyle = FormBorderStyle.Sizable;
            view.Location = new Point(0, 0);
            view.TopMost = true;
            view.Show();
        }
        
        // 弹Terminal窗口
        void OnTerminalEventHandlerShow()
        {
            CMyFormEx pTerminal = GetViewForMap("Terminal");//new TerminalView();
            if (!"终端服务".Equals(m_curActiveView.m_pViewName))
            {
                panelShow.Controls.Remove(pTerminal);
                pTerminal.FormBorderStyle = FormBorderStyle.Sizable;
                pTerminal.Location = new Point(0, 0);
                pTerminal.TopLevel = true;
                pTerminal.Show();
            }
        }

        public void ChangeNodeTag(TreeNodeCollection nodes)
        {
            if (nodes.Count == 0)
            {
                return;
            }
            foreach (TreeNode item in nodes)
            {
                item.Tag = "Pass";
                ChangeNodeTag(item.Nodes);
            }
        }
        public override void OnPasswordLogin(int permission)
        {
            ChangePermission(treeViewFunc.Nodes, permission);
        }

        public void ChangePermission(TreeNodeCollection nodes, int permission)
        {
            if (nodes.Count == 0)
            {
                return;
            }
            foreach (TreeNode item in nodes)
            {
                if (permission == 1)
                {
                    item.ForeColor = new Color();
                    item.Tag = "Pass";
                }
                else if (permission == 0)
                {
                    if (item.Text == "Equip" || item.Text == "Connect" || item.Text == "PJob" || item.Text == "CJob" || item.Text == "Logs")
                    {
                        item.ForeColor = new Color();
                        item.Tag = "Pass";
                    }
                    else
                    {
                        item.ForeColor = Color.LightGray;
                        item.Tag = "";
                    }
                }
                ChangePermission(item.Nodes, permission);
            }
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            Quit();
            CloseAllChildView();
            base.OnClosing(e);
        }

        // 关闭子窗口
        protected void CloseAllChildView()
        {
            foreach (CMyFormEx pView in m_mapView.Values)
            {
                try
                {
                    pView.Close();
                }
                catch (System.Exception)
                {

                }
            }
        }

        public void Quit()
        {
            secsEquipHelper.Quit();
        }

        private void SecsMainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!SecsEquipHelper.IsCreateSelf)
            {
                e.Cancel = true;
                this.Hide();
            }
        }
    }
}
